#include "server_test.h"

#include <SFML/Window.hpp>

#include "../debug.hpp"
#include "../lge2d.hpp"

namespace lls = lge2d::lan::server;
namespace llan = lge2d::lan;

using namespace lge2d;


ServerTest::ServerTest(sf::RenderWindow * window) :
	m_window(window)
{
}

void ServerTest::Initialize()
{
	const char font[] = "UbuntuMono-R.ttf";
	if (!m_font.LoadFromFile(font, 20))
	{
		fire_exception("can't load font file %s", font);
	}

	m_serverStatus.SetFont(m_font);
	m_serverStatus.SetSize((float) 20);
	m_serverStatus.SetPosition(10, 10);
	m_serverStatus.SetText("Server state: stopped");
}

void ServerTest::Update(float dt)
{
	m_clientConnection.Update(dt);
	m_server.Update(dt);

	if (m_prevServerState != m_server.GetState())
	{
		lls::Server::ServerState serverState = m_server.GetState();

		switch(serverState)
		{
		case lls::Server::ServerIsStarting:
			m_serverStatus.SetText("Server state: starting");
			break;

		case lls::Server::ServerIsStarted:
			m_serverStatus.SetText("Server state: started");
			break;

		case lls::Server::ServerIsWorking:
			m_serverStatus.SetText("Server state: working");
			break;

		case lls::Server::ServerIsStopping:
			m_serverStatus.SetText("Server state: stopping");
			break;

		case lls::Server::ServerIsStopped:
			m_serverStatus.SetText("Server state: stopped");
			break;
		}
		m_prevServerState = serverState;
	}
}

void ServerTest::OnEvent(const sf::Event *event)
{
	if (event->Type == sf::Event::KeyPressed && event->Key.Code == sf::Key::S)
	{
		lls::Server::ServerState serverState = m_server.GetState();
		if (serverState == lls::Server::ServerIsStopped)
		{
			m_server.Start();
		}
		else if (serverState == lls::Server::ServerIsWorking)
		{
			m_server.Stop();
		}
	}

	if (event->Type == sf::Event::KeyPressed && event->Key.Code == sf::Key::T)
	{
		llan::Connection::State st = m_clientConnection.GetState();
		if (st == llan::Connection::Disconnected)
		{
			llan::Connection::ErrorCode res = m_clientConnection.Connect("localhost");

			switch (res)
			{
			case llan::Connection::NoError:
				break;

			default:
				lge2d::log->Info("Can't connect.");
				break;
			}
		}
		else if (st == llan::Connection::Connected)
		{
			m_clientConnection.Disconnect();
		}
	}
}

void ServerTest::Render() const
{
	m_window->Clear();
	m_window->Draw(m_serverStatus);
}

ServerTest::~ServerTest()
{
	m_window = NULL;
}
